package cn.chenddcoder;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONUtil;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Tree2path {
    public static String getPath(String str,Stack<String> stack,int depth){
        List<String> pathList=new ArrayList<>();
        for (int i=0;i<depth-1;i++){
            pathList.add(stack.get(i));
        }
        pathList.add(str);
        return CollUtil.join(pathList,"/");
    }
    public static void main(String[] args) {
        List<String> lines = FileUtil.readLines("~/Desktop/tree.txt", "utf8");
        int depth=0;
        int lineNum=0;
        int oldDepth=0;
        int oldIndex=0;
        Stack<String> stack=new Stack<>();
        List<String> outLines=new ArrayList<>();
        Map<Integer,Integer>  indexToDepth=new HashMap<>();
        for (String line:lines){
//            //depth这么判断不太行，因为竖线规则不固定
//            depth=ReUtil.count("[├│└]",line);
//            if (depth==0){
//                continue;
//            }
            //取符号后面的字符串
            String str=ReUtil.get("── (.*)$",line,1);
            if (ObjectUtil.isEmpty(str)){
                continue;
            }
            int index=line.indexOf(str);
            if (index>oldIndex){
                depth++;
                indexToDepth.put(index,depth);
            }else if(index<oldIndex){
                if (indexToDepth.containsKey(index)){
                    depth=indexToDepth.get(index);
                }
            }
            System.out.println("depth:"+depth+" oldDepth:"+oldDepth);
            if (depth>oldDepth){
            }else if(depth<oldDepth){
                for (int i=0;i<=oldDepth-depth;i++){
                    stack.pop();
                }
            }else {
                stack.pop();
            }
            stack.push(str);
            String path = getPath(str, stack, depth);
            outLines.add(path);
            System.out.println(path);
            lineNum++;
            oldDepth=depth;
            oldIndex=index;
//            if (lineNum==180){
//                break;
//            }
        }
        FileUtil.writeLines(outLines,"~/Desktop/tree_out.txt","utf8");
    }
}
